package com.huangliusong.quickstart;

import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author huangliusong
 * @since 2018/11/25
 * {@link }
 */
public class Main {
    public static void main(String[] args) {
        long start=System.currentTimeMillis();
        OrderEvenFactory orderEvenFactory=new OrderEvenFactory();
        int ringBufferj=1024*1024;
        ExecutorService executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        //1.实例一个disruptor对象
        Disruptor<OrderEvent> disruptor=new Disruptor<OrderEvent>(
                orderEvenFactory,
                //容器的长度
                ringBufferj,
                //线程池需要自定义的，用拒绝策略
                executorService,
                //单生产者还是多生产者
                ProducerType.SINGLE,
                //等待策略
                new BlockingWaitStrategy()
        );

        //2。添加消费者的disruptor与消费者构建一个关联关系
        disruptor.handleEventsWith(new OrderEventHandler());
        //3启动disruptor
        disruptor.start();

        //4创建生产者 获得实际存储数据的容器 RingBuffer
        RingBuffer<OrderEvent> ringBuffer=disruptor.getRingBuffer();


        OrderEvenProducer orderEvenProducer=new OrderEvenProducer(ringBuffer);

        ByteBuffer bb= ByteBuffer.allocate(8);

        for (long i=0;i<100;i++){
            bb.putLong(0,i);
            orderEvenProducer.sendData(bb);
        }
        disruptor.shutdown();
        executorService.shutdown();
        long end=System.currentTimeMillis();
        System.out.println((end-start)+"ms耗时");
    }
}
